package cn.ijero.pictureselector.demo;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import java.util.List;

import cn.ijero.pictureselector.PictureSelector;
import cn.ijero.pictureselector.callback.PictureSelectorCallback;
import cn.ijero.pictureselector.data.LocalMedia;
import cn.ijero.pictureselector.demo.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding binding;
    private final int requestCode = 1000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        initViewListener();
    }

    private void initViewListener() {
        binding.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
                    return;
                }
                PictureSelector.with(MainActivity.this).load(new PictureSelectorCallback() {
                    @Override
                    public void onSelected(List<LocalMedia> checked) {
                        binding.detailTextView.setText(checked.toString());
                    }
                });
            }
        });
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == this.requestCode) {
            boolean isGrantedAll = true;

            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    isGrantedAll = false;
                    break;
                }
            }

            if (!isGrantedAll) {
                Toast.makeText(this, "请先授予权限", Toast.LENGTH_SHORT).show();
            }
        }
    }
}